package org.aeon.client.view.components.button;

import org.aeon.client.context.GlobalContext;
import org.aeon.client.view.ApplicationUI;
import org.aeon.client.view.components.listColumn.GroupCreationDialog;
import org.aeon.entity.User;
import org.aeon.message.request.GroupCreateRequestMessage;
import org.aeon.message.request.ListQueryRequestMessage;
import org.aeon.utils.ImageSetUtil;
import org.aeon.utils.SimpleRequestUtil;
import org.aeon.utils.SwingUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.aeon.client.context.MessageMap.MessageContextKey.MemberList;

/**
 * @author: MissingAeon
 * @date: 2024/2/28 17:07
 * @description:
 */
public class ExpansionButton extends JButton {
    private final String[] options;
    private final JButton[] buttons;
    private JPanel dropdownPanel;
    private List<Runnable> listenerFuture;

    private ExpansionButton(Dimension dimension, String... options) {
        super(new ImageIcon(ImageSetUtil.getImage("expansion", 20, 20)));
        this.setMargin(new Insets(0, 0, 0, 0));
        this.options = options;
        this.buttons = new JButton[options.length];
        // 禁用按钮获取焦点时的虚线框
        this.setFocusPainted(false);
        // 禁用按钮的焦点功能
        // this.setFocusable(false);

        // this.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
        this.setBackground(Color.WHITE);

        SwingUtil.setSize(this, dimension);

        this.addActionListener(e -> {
            if (dropdownPanel == null) createDialog();
            // if (display) hideList();
            // else
            // TODO 二次点击隐藏
            GlobalContext.getContext().getMainUI().addPopUpLayer(dropdownPanel);
            dropdownPanel.requestFocus();
        });
    }

    /**
     * 创建扩展按钮
     *
     * @return
     */
    public static ExpansionButton createExpansionButton() {
        final ExpansionButton expansion = new ExpansionButton(new Dimension(29, 29), "创建群聊", "找群/找人");

        SwingUtilities.invokeLater(() -> {
            expansion.addActionListener("创建群聊", e -> {
                // TODO 群名输入框
                createSetGroupNameDialog();
            });
        });

        return expansion;
    }

    private static void createSetGroupNameDialog() {
        final GlobalContext context = GlobalContext.getContext();
        final ApplicationUI mainUI = context.getMainUI();

        final JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBounds(mainUI.getWidth() / 2 - 150, mainUI.getHeight() / 2 - 100, 300, 200);

        panel.add(Box.createVerticalStrut(30));

        final JLabel label = new JLabel("群名称");
        label.setFont(new Font("黑体", Font.PLAIN, 18));
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(label);
        panel.add(Box.createVerticalStrut(15));


        final JTextField textField = new JTextField(20);
        textField.setFont(new Font("黑体", Font.PLAIN, 16));
        textField.setAlignmentX(Component.CENTER_ALIGNMENT);
        SwingUtil.setSize(textField, new Dimension(250, 35));
        panel.add(textField);
        panel.add(Box.createVerticalStrut(15));

        final Box box = Box.createHorizontalBox();
        box.add(Box.createHorizontalGlue());
        final JButton submitBut = new OperationButton("确认", new Color(0x10ABDA));
        box.add(submitBut);

        box.add(Box.createHorizontalStrut(20));
        final JButton cancelBut = new OperationButton("取消", Color.GRAY);
        box.add(cancelBut);
        box.add(Box.createHorizontalGlue());

        panel.add(box);
        panel.add(Box.createVerticalGlue());

        final JPanel mask = SwingUtil.createMask(mainUI.getWidth(), mainUI.getHeight() - 30);

        mask.add(panel);
        mainUI.addPopUpLayer(mask);

        submitBut.addActionListener(e -> {
            final String text = textField.getText();
            if (text.isEmpty()) return;
            mask.remove(panel);
            createGroupCreationDialog(mask, text);
        });
        cancelBut.addActionListener(e -> mainUI.removePopUpLayer(mask));

    }

    private static void createGroupCreationDialog(JPanel masking, String title) {
        final GlobalContext context = GlobalContext.getContext();
        final ApplicationUI mainUI = context.getMainUI();
        final GroupCreationDialog dialog = new GroupCreationDialog();

        context.getThreadPool().execute(() -> {
            final User currentUser = context.getCurrentUser();
            SimpleRequestUtil.sendAndWait(context, new ListQueryRequestMessage(currentUser.getId(), true),
                    () -> SwingUtilities.invokeLater(() -> dialog.dataFilling(context.getMessageMap().del(MemberList), title)));
        });

        dialog.addSubmitHandle(() -> context.getThreadPool().execute(() -> {
            final Set<Long> set = dialog.getButtons().stream()
                    .filter(CheckButton::isCheck)
                    .map(button -> button.getContent().getId()).collect(Collectors.toSet());
            SimpleRequestUtil.sendAndWait(context, new GroupCreateRequestMessage(context.getCurrentUser().getId(), title, set),
                    () -> SwingUtilities.invokeLater(() -> {
                        mainUI.removePopUpLayer(masking);
                        // TODO 成功后跳转
                        // final GroupInfoPanel panel = new GroupInfoPanel(sessionPanel);
                        // panel.fillInData(context.getMessageMap().del(GroupInfo));
                        // sessionPanel.add(panel);
                    }));
        }));

        dialog.addCancelHandle(() -> mainUI.removePopUpLayer(masking));
        masking.add(dialog);
    }

    private void createDialog() {
        dropdownPanel = new JPanel();
        dropdownPanel.setLayout(new BoxLayout(dropdownPanel, BoxLayout.Y_AXIS));
        dropdownPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
        dropdownPanel.setBackground(Color.WHITE);

        final Dimension dimension = new Dimension(110, 35);
        final ApplicationUI mainUI = GlobalContext.getContext().getMainUI();
        for (int i = 0; i < options.length; i++) {
            final JButton button = new JButton(options[i]);
            buttons[i] = button;
            button.setMargin(new Insets(0, 0, 0, 0));
            addItem(button, dimension);
        }
        listenerFuture.forEach(Runnable::run);
        dropdownPanel.setBounds(this.getLocationOnScreen().x - mainUI.getLocationOnScreen().x + this.getWidth() - mainUI.getInsets().left,
                this.getLocationOnScreen().y - mainUI.getLocationOnScreen().y - mainUI.getInsets().top - 1,
                dimension.width, (dimension.height + 2) * options.length + 2);

        dropdownPanel.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                mainUI.removePopUpLayer(dropdownPanel);
            }
        });

    }

    /**
     * 添加列表项组件
     *
     * @param button
     */
    public void addItem(JButton button, Dimension dimension) {
        SwingUtil.removeStyle(button);

        button.setPreferredSize(dimension);
        button.setMinimumSize(dimension);
        button.setMaximumSize(dimension);

        button.setFont(new Font("黑体", Font.PLAIN, 14));
        dropdownPanel.add(Box.createVerticalStrut(1));
        dropdownPanel.add(button);
        dropdownPanel.add(Box.createVerticalStrut(1));
        // 鼠标悬浮事件
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setContentAreaFilled(true);
                button.setBackground(Color.lightGray);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setContentAreaFilled(false);
            }
        });

        button.addActionListener(e -> {
            GlobalContext.getContext().getMainUI().removePopUpLayer(dropdownPanel);
            button.setContentAreaFilled(false);
        });
    }

    /**
     * 为一个按钮添加一个事件
     * 当按钮创造时
     *
     * @param text
     * @param listener
     */
    public void addActionListener(String text, ActionListener listener) {
        if (listenerFuture == null) listenerFuture = new ArrayList<>();
        listenerFuture.add(() -> Arrays.stream(buttons)
                .filter(button -> button.getText().equals(text))
                .findAny()
                .ifPresent(button -> button.addActionListener(listener)));
    }
}
